package cn.li.security.jwt.service;


import io.jsonwebtoken.Claims;
import lombok.Setter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import io.jsonwebtoken.Clock;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.DefaultClock;
import org.springframework.security.core.userdetails.UserDetails;

public class DefaultJwtService implements IJwtService {
    public static final String AUTHENTICATION_SCHEME_JWT = "Bearer";
    public static final long ExpireIntTime = 72 * 3600 * 1000L;
    public static final String DEFAULT_SIGNING_KEY = "default";

    @Setter
    private Long expireIn = ExpireIntTime;

    @Setter
    private String authenticationScheme = AUTHENTICATION_SCHEME_JWT;

    @Setter
    private String signingKey = DEFAULT_SIGNING_KEY;

    private Clock clock = DefaultClock.INSTANCE;




    @Override
    public JwtResult generator(Map<String,Object> claims) {
        final Date createdDate = clock.now();
        final Date expirationDate = calculateExpirationDate(createdDate);
        String token = authenticationScheme + " " + Jwts.builder()
                .setClaims(claims)
                .setSubject((String) claims.get("username"))
                .setIssuedAt(createdDate)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, signingKey)
                .compact();
        return new JwtResult(token,this.expireIn);
    }

    @Override
    public JwtResult generator(UserDetails userDetails) {
        Map<String,Object> claims = new HashMap<>();
        claims.put("username",userDetails.getUsername());
        return this.generator(claims);
    }

    @Override
    public Object retrieve(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(signingKey)
                .parseClaimsJws(token)
                .getBody();
        return claims.getSubject();
    }



    private Date calculateExpirationDate(Date createdDate) {
        return new Date(createdDate.getTime() + expireIn);
    }

    @Override
    public String getAuthenticationScheme() {
        return this.authenticationScheme;
    }
}
